package com.appbee.cm.client.nav.ui;

import javax.inject.Inject;

import com.appbee.cm.client.nav.presenter.NavItemWrap;
import com.appbee.cm.client.nav.presenter.NavSelectionBoxPresenter;
import com.appbee.cm.client.nav.presenter.NavTreeViewModel;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

public class NavSelectPopup extends Composite implements
		NavSelectionBoxPresenter.SelectView
{
	private final PopupPanel popupPanel = new PopupPanel();
	private final FlowPanel panel = new FlowPanel();
	private final CellTree tree;
	private final Button rootSelect = new Button("Root");
	private NavSelectionBoxPresenter presenter;
	private final SingleSelectionModel<NavItemWrap> selectionModel;

	@Inject
	public NavSelectPopup(final NavTreeViewModel navTreeViewModel)
	{
		this.selectionModel = navTreeViewModel.getSelectionModel();
		navTreeViewModel.setCell(new NavCell());
		tree = new CellTree(navTreeViewModel, null);
		panel.add(rootSelect);
		panel.add(tree);
		initWidget(panel);
		popupPanel.setWidget(this);
		popupPanel.setAutoHideEnabled(true);
		navTreeViewModel.getSelectionModel()
				.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
				{

					@Override
					public void onSelectionChange(SelectionChangeEvent event)
					{
						presenter.onNavSelected(selectionModel
								.getSelectedObject());
					}
				});
		rootSelect.addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				presenter.onNavSelected(null);
			}
		});
	}

	@Override
	public void setPresenter(NavSelectionBoxPresenter presenter)
	{
		this.presenter = presenter;
	}

	@Override
	public void setSelectedValue(NavItemWrap value)
	{
		if (value == null)
		{
			NavItemWrap selectedObject = selectionModel.getSelectedObject();
			if (selectedObject != null)
				selectionModel.setSelected(selectedObject, false);
		}
		else
			selectionModel.setSelected(value, true);
	}

	@Override
	public void show(Object source)
	{
		popupPanel.showRelativeTo((UIObject) source);
	}

	@Override
	public void hide()
	{
		popupPanel.hide();
	}

	public class NavCell extends AbstractCell<NavItemWrap>
	{

		@Override
		public void render(	Context context,
							NavItemWrap value,
							SafeHtmlBuilder sb)
		{
			sb.appendEscaped(value.getName());
		}

	}

}
